package com.unify.python.http;

import com.alibaba.fastjson.JSONObject;
import com.unify.python.config.PythonConfig;
import com.unify.python.model.IPProxy;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @Author: wchen
 * @Description:
 * @Date: Created in 2018-12-18 16:11
 * Copyright 本内容仅限于杭州阿拉丁信息科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
public class PythonHttpClient {

    private static Logger logger = LoggerFactory.getLogger(PythonHttpClient.class);

    /**
     * 获取网页内容
     * @param uri
     * @param headInfo
     * @param ipProxy
     * @return
     */
    public static String doGet(String uri, Map<String, String> headInfo, IPProxy ipProxy){


        HttpGet httpGet = new HttpGet(uri);     //创建httpget实例
        //添加请求配置
        setRequestConfig(httpGet, ipProxy);
        //添加头部信息
        setHeaderInfo(headInfo, httpGet);

        String html = executeRequest(httpGet);

        return html;
    }


    /**
     * 执行请求
     * @param httpRequestBase
     * @return
     */
    private static String executeRequest(HttpRequestBase httpRequestBase){
        CloseableHttpClient httpClient = HttpConnectionPoolClient.getHttpClient();    //获取httpClient实例
        try {
//            HttpHost proxy=new HttpHost("61.128.208.94", 3128);
//            RequestConfig requestConfig=RequestConfig.custom().setProxy(proxy).build();
//            httpRequestBase.setConfig(requestConfig);
//            httpRequestBase.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
//



            HttpResponse response = httpClient.execute(httpRequestBase); // 执行http get请求
            HttpEntity entity = response.getEntity(); // 获取返回实体
            String html = EntityUtils.toString(entity, "utf-8");
            System.out.println("网页内容：" + html); // 获取网页内容
            return html;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            try {
                httpClient.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }

    /*****************************************************私有方法***************************************************/

    /**
     * 设置请求config
     * @param requestBase   请求基类
     * @param ipProxy       代理ip
     */
    private static void setRequestConfig(HttpRequestBase requestBase, IPProxy ipProxy){
        HttpHost proxy = new HttpHost(ipProxy.getHost(), ipProxy.getPort());
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(PythonConfig.connectionTimeout)
                .setSocketTimeout(PythonConfig.socketTimeout)
                .setProxy(proxy)
                .build();
        requestBase.setConfig(requestConfig);
    }


    /**
     * 添加头部信息
     * @param headInfo      头部信息
     * @param httpMessage   http请求
     */
    private static void setHeaderInfo(Map<String, String> headInfo, HttpMessage httpMessage){
        //浏览器头部
        httpMessage.addHeader(HttpRandomHeaderClient.createUserAgentHeader());
        //自定义头部
        if(Objects.isNull(headInfo)){
            return ;
        }
        Set<Map.Entry<String, String>> headEntrySet = headInfo.entrySet();
        headEntrySet.forEach(stringStringEntry -> httpMessage.addHeader(stringStringEntry.getKey(), stringStringEntry.getValue()));
    }


    /**
     * 设置post请求的参数
     * @param httpPost
     * @param params
     */
    private static void setPostParams(HttpPost httpPost, Map<String, String> params){
        List<NameValuePair> nvps = new ArrayList<>();
        Set<String> keys = params.keySet();
        for (String key: keys){
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}
